<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 查询、筛选条件 -->

      <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-position="left" label-width="85px">
        <el-row :gutter="48">
          <el-col :xs="24" :sm="8">
            <el-form-item label="公告标题：" prop="noticeTitle">
              <el-input v-model="queryParams.noticeTitle" placeholder="请输入公告标题" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8">
            <el-form-item label="操作人员：" prop="createBy">
              <el-input v-model="queryParams.createBy" placeholder="请输入操作人员" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <!-- 高级筛选 默认隐藏 -->
          <template v-if="advanced">
            <el-col :xs="24" :sm="8">
              <el-form-item label="类型：" prop="noticeType">
                <el-select v-model="queryParams.noticeType" placeholder="公告类型" clearable size="small" style="width: 100%">
                  <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :xs="24" :sm="!advanced && 8 || 24">
            <span class="search-advancedButton">
              <el-button type="primary" size="small" @click="handleQuery">查 询</el-button>
              <el-button size="small" @click="resetQuery">重 置</el-button>
              <el-button type="text" @click="advanced = !advanced">
                {{ advanced ? '收起' : '展开' }}
                <i :class="[!advanced && 'arrow-up' || 'arrow-down' ,'el-icon-arrow-up']" />
              </el-button>
            </span>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格左侧按钮 -->
      <el-row :gutter="10" class="mb16">
        <el-col :span="1.5">
          <el-button v-hasPermi="['system:notice:add']" type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </el-col>
        <transition name="el-fade-in-linear">
          <el-col v-if="ids.length > 0" :span="1.5">
            <el-button v-hasPermi="['system:notice:remove']" type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
        </transition>

        <!-- 表格右侧工具栏 -->
        <right-toolbar :show-search.sync="showSearch" :show-ding.sync="showDingDing" @queryTable="getList" />
      </el-row>

      <el-table ref="noticeTable" v-loading="loading" row-key="noticeId" :data="noticeList" @selection-change="handleSelectionChange">
        <template slot="empty">
          <el-empty />
        </template>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="noticeId" width="100" />
        <el-table-column label="公告标题" align="center" prop="noticeTitle" :show-overflow-tooltip="true" />
        <el-table-column label="公告类型" align="center" prop="noticeType" :formatter="typeFormat" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="{row}">
            <el-dot :type="row.status === '0' ? 'primary' :'error'" />
            <span class="badge-status-text">{{ statusFormat(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="createBy" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
          <template slot-scope="{row}">
            <span>{{ parseTime(row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-hasPermi="['system:notice:edit']" size="small" type="text" @click="handleUpdate(row)">修改</el-button>
            <el-divider direction="vertical" />
            <el-button v-hasPermi="['system:notice:remove']" size="small" type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改公告对话框 -->
      <zrk-drag-dialog ref="dialogDemo" :title="title" :width="'780px'" :show.sync="open" :is-footer="true" :append-to-body="true">
        <div slot="body">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="48">
              <el-col :span="12">
                <el-form-item label="公告标题" prop="noticeTitle">
                  <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公告类型" prop="noticeType">
                  <select-dict-tag v-model="form.noticeType" dict-code="sys_notice_type" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="状态">
                  <select-dict-tag v-model="form.status" dict-code="sys_notice_status" type="radio" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="内容">
                  <editor v-model="form.noticeContent" :min-height="192" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div slot="footer" class="text-right">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </zrk-drag-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  listNotice,
  getNotice,
  delNotice,
  addNotice,
  updateNotice
} from '@/api/system/notice'
import Editor from '@/components/Editor'
import Sortable from 'sortablejs'

export default {
  name: 'Notice',
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示钉钉
      showDingDing: true,
      // 高级查询
      advanced: false,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 初始化sortable
      sortable: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      statusOptions: [],
      // 状态数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        noticeType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        noticeType: [
          { required: true, message: '公告类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_notice_status').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_notice_type').then((response) => {
      this.typeOptions = response.data
    })
  },
  methods: {
    /** 查询公告列表 */
    async getList() {
      this.loading = true
      await listNotice(this.queryParams).then((response) => {
        this.noticeList = response.rows
        this.total = response.total
        this.loading = false
        this.$nextTick(() => {
          this.setSort()
        })
      })
    },
    /* 表格拖拽功能 sortable.js http://www.sortablejs.com/options.html */
    setSort() {
      const el = this.$refs.noticeTable.$el.querySelectorAll(
        '.el-table__body-wrapper > table > tbody'
      )[0]
      const self = this
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: (dataTransfer) => {
          dataTransfer.setData('Text', '')
        },
        onEnd: ({ newIndex, oldIndex }) => {
          const targetRow = self.noticeList.splice(oldIndex, 1)[0]
          self.noticeList.splice(newIndex, 0, targetRow)
        }
      })
    },
    // 公告状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 公告状态字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.noticeType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.noticeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加公告'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const noticeId = row.noticeId
      getNotice(noticeId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改公告'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.noticeId !== undefined) {
            updateNotice(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addNotice(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeIds = row.noticeId || this.ids
      this.$confirm(
        '是否确认删除公告编号为"' + noticeIds + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          return delNotice(noticeIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    }
  }
}
</script>

<style >
.sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #409eff !important;
}
</style>
